package com.wxscrmplus.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxscrmplus.common.constant.CacheConstants;
import com.wxscrmplus.common.core.domain.entity.SysUser;
import com.wxscrmplus.common.utils.StringUtils;
import com.wxscrmplus.common.core.page.TableDataInfo;
import com.wxscrmplus.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wxscrmplus.common.utils.redis.RedisUtils;
import com.wxscrmplus.customer.domain.Customer;
import com.wxscrmplus.customer.domain.vo.CustomerVo;
import com.wxscrmplus.customer.mapper.CustomerMapper;
import com.wxscrmplus.system.mapper.SysUserMapper;
import com.wxscrmplus.wxcp.factory.WxCpServiceFactory;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpMessageService;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import org.springframework.stereotype.Service;
import com.wxscrmplus.customer.domain.bo.FollowRecordBo;
import com.wxscrmplus.customer.domain.vo.FollowRecordVo;
import com.wxscrmplus.customer.domain.FollowRecord;
import com.wxscrmplus.customer.mapper.FollowRecordMapper;
import com.wxscrmplus.customer.service.IFollowRecordService;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 跟进记录Service业务层处理
 *
 * @author 王永超
 * @date 2023-03-25
 */
@RequiredArgsConstructor
@Service
public class FollowRecordServiceImpl extends WxCpServiceFactory implements IFollowRecordService {

    private final FollowRecordMapper baseMapper;
    private final CustomerMapper customerMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询跟进记录
     */
    @Override
    public FollowRecordVo queryById(Long followRecordId) {
        FollowRecordVo followRecordVo = baseMapper.selectVoById(followRecordId);
        followRecordVo.setUserNickName(userMapper.findNickNameById(followRecordVo.getUserId()));
        return followRecordVo;
    }

    /**
     * 查询跟进记录列表
     */
    @Override
    public TableDataInfo<FollowRecordVo> queryPageList(FollowRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FollowRecord> lqw = buildQueryWrapper(bo);
        Page<FollowRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (FollowRecordVo record : result.getRecords()) {
            record.setUserNickName(userMapper.findNickNameById(record.getUserId()));
            CustomerVo customerVo = customerMapper.selectVoById(record.getCustomerId());
            record.setCustomerName(customerVo.getName());
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询跟进记录列表
     */
    @Override
    public List<FollowRecordVo> queryList(FollowRecordBo bo) {
        LambdaQueryWrapper<FollowRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FollowRecord> buildQueryWrapper(FollowRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FollowRecord> lqw = Wrappers.lambdaQuery();
// c670dde58cdac271eb21aa6e8cb3431a
        lqw.eq(bo.getCustomerId() != null, FollowRecord::getCustomerId, bo.getCustomerId());
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), FollowRecord::getTitle, bo.getTitle());
        lqw.in(CollectionUtil.isNotEmpty(bo.getDataRangeUserIds()), FollowRecord::getUserId, bo.getDataRangeUserIds());
        lqw.orderByDesc(FollowRecord::getFollowRecordId);
        return lqw;
    }

    /**
     * 新增跟进记录
     */
    @Override
    public Boolean insertByBo(FollowRecordBo bo) {
        FollowRecord add = BeanUtil.toBean(bo, FollowRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setFollowRecordId(add.getFollowRecordId());
        }
        //更新最近跟进时间
        Customer customer = new Customer();
        customer.setCustomerId(bo.getCustomerId());
        customer.setLaterFollowTime(new Date());
        customerMapper.updateById(customer);
        return flag;
    }

    /**
     * 修改跟进记录
     */
    @Override
    public Boolean updateByBo(FollowRecordBo bo) {
        FollowRecord update = BeanUtil.toBean(bo, FollowRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FollowRecord entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除跟进记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 明天的跟进记录提醒成员跟进
     */
    @Override
    public void timingRemindTomorrow() {
        QueryWrapper<FollowRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FollowRecord::getFollowRemind, FollowRecord.FollowRemindFieldEnums.YES.getValue());
        queryWrapper.lambda().between(FollowRecord::getFollowTime,
            LocalDateTimeUtil.now().withHour(23).withMinute(59).withSecond(59),
            LocalDateTimeUtil.now().plusDays(2).withHour(0).withMinute(0).withSecond(0));
        List<FollowRecord> followRecordList = baseMapper.selectList(queryWrapper);
        for (FollowRecord followRecord : followRecordList) {
            String key = CacheConstants.FOLLOW_RECORDS_ALREADY_REMIND + followRecord.getFollowRecordId();
            Object cacheObject = RedisUtils.getCacheObject(key);
            if (ObjectUtil.isNotNull(cacheObject)) {
                continue;
            }
            SysUser sysUser = userMapper.selectById(followRecord.getUserId());
            CustomerVo customerVo = customerMapper.selectVoById(followRecord.getCustomerId());
            //发送企微信息通知成员
            WxCpMessageService messageService = getMessageService();
            WxCpMessage wxCpMessage = new WxCpMessage();
            wxCpMessage.setTitle(followRecord.getTitle());
            wxCpMessage.setMsgType("text");
            wxCpMessage.setContent("客户跟进提醒" + "\n" +
                "摘要：" + followRecord.getTitle() + "\n" +
                "客户：" + customerVo.getName() + "\n" +
                "跟进时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(followRecord.getFollowTime())
            );
            wxCpMessage.setToUser(sysUser.getUserName());
            try {
                messageService.send(wxCpMessage);
            } catch (WxErrorException e) {
                throw new RuntimeException(e);
            }
            RedisUtils.setCacheObject(key, "1", Duration.ofDays(3));
        }
    }
}
